package com.luban.springboot.controller;

import java.io.InputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadExcelController {
	
	@RequestMapping("/file")
	public String file() {
		return "file";
	}

	/**
	 * 上传文件
	 * @param modle
	 * @param file
	 * @return
	 */
	@RequestMapping(value="/uploadFile",produces="application/json;charset=UTF-8")
    public String uploadFile(Model modle, @RequestParam(value = "excelFile") MultipartFile file){
		String result = "";
		try {
			InputStream inputStream = file.getInputStream();
	        String fileName = file.getOriginalFilename();
	        Workbook wb;
	        
	        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
	            wb = new XSSFWorkbook(inputStream);
	        } else {
	            wb = new HSSFWorkbook(inputStream);
	        }
	        
	        Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                result="Excel数据为空！";
                return result;
            }
            
            // 列数
            int column = sheet.getRow(0).getPhysicalNumberOfCells();
            // 行数
            int rows = sheet.getLastRowNum();
          
            for (int i = 1; i <= rows; i++) {
            	Row row = sheet.getRow(i);
                for(int j = 0; j < column; j++) {
                	if (row.getCell(j) != null) {
                		row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                		result += row.getCell(j).getStringCellValue()+"----";
                    }
                }
                result+="第"+i+"行取完---";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "上传失败";
		}
		modle.addAttribute("msg",result);
		return "file";
	}
}
